package com.hty.notes;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.util.Date;

public class NoteActivity extends Activity {

    EditText editText;
    InputMethodManager IMM;
    String s="";
    long id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        Intent intent = getIntent();
        id = intent.getLongExtra("id", -1);
        Log.e(Thread.currentThread().getStackTrace()[2] + "", "id = " + id);
        editText = (EditText) findViewById(R.id.editText);

        if (id != 1) {
            DBHelper helper = new DBHelper(this);
            Cursor cursor = helper.queryId(id);
            if (cursor.moveToFirst()) {
                s = cursor.getString(cursor.getColumnIndex("note"));
                editText.setText(s);
            }
        }

        IMM = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        //IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);//无效
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);//无效
        menu.add(0, 0, 0, "分享");
        menu.add(0, 1, 1, "保存");
        menu.add(0, 2, 2, "退出");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                String[] items = { "文字", "图片"};
                AlertDialog.Builder dialog;
                dialog = new AlertDialog.Builder(NoteActivity.this);
                dialog.setTitle("分享");
                dialog.setIcon(android.R.drawable.ic_menu_share);
                dialog.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_TEXT, editText.getText().toString());
                                intent.setType("text/plain");
                                startActivity(Intent.createChooser(intent, "分享到"));
                                break;
                            case 1:
                                //https://blog.csdn.net/qq_24823401/article/details/83687515
                                Bitmap bitmap = textToBitmap(editText.getText().toString(), 60, Color.BLACK);
                                //保存bitmap到存储，插入数据到媒体库，获取图片的uri
                                Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), bitmap, null, null));
                                intent = new Intent();
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_STREAM, uri);
                                intent.setType("image/*");
                                startActivity(Intent.createChooser(intent, "分享到"));
                                break;
                        }
                    }
                });
                dialog.show();
                break;
            case 1:
                save();
                break;
            case 2:
                IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                finish();
                break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            save();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    void save() {
        DBHelper DBHelper = new DBHelper(getApplicationContext());
        SQLiteDatabase DB = DBHelper.getWritableDatabase();
        Date date = new Date();
        String s1 = editText.getText().toString();
        ContentValues values = new ContentValues();
        values.put("time", date.getTime());
        values.put("note", s1);
        if (id == -1) {
            if (!s1.equals(""))
                id = DB.insert("notes", null, values);
        } else {
            if (!s.equals(s1))
                DB.update("notes", values, "_id = " + id, null);
        }
        DB.close();
    }

    //图片转文字：https://www.cnblogs.com/yongfengnice/p/13640108.html
    //图片转文字换行：https://www.cnblogs.com/error404/archive/2013/01/25/2876901.html
    Bitmap textToBitmap(String text, int textSize, int textColor) {
        TextPaint textPaint = new TextPaint();
        //textPaint.setAntiAlias(true); //无效
        textPaint.setTextSize(textSize);
        textPaint.setColor(textColor);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        StaticLayout SL = new StaticLayout(text, textPaint, width - 100, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); //换行
        int height = SL.getHeight() + 100;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        canvas.drawColor(Color.WHITE); //背景
        canvas.translate(50, 50); //边距
        SL.draw(canvas);
        return bitmap;
    }

}